package net.loyin.app.model;

import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import net.loyin.annotation.TableBind;
import net.loyin.app.Constant;
import net.loyin.app.model.base.BaseArticle;

import java.util.ArrayList;
import java.util.List;

/**
 * 文章
 */
@SuppressWarnings("serial")
@TableBind(tableName = Article.tableName)
public class Article extends BaseArticle<Article> {
	public static final String tableName="article";
	public static final Article dao = new Article();

	/**
	 * 更新阅读次数
	 * @param id
     */
	public void updateReadCount(String id) {
		Db.update("update article set read_count=read_count+1 where id=?",id);
	}
	public Article qryById(String id){
		return this.findFirst("select a.*,ac.name cate_name,acp.name pcate_name from "+tableName+" a left join "+ArticleCate.tableName+" ac on ac.id=a.cate_id left join "+ArticleCate.tableName+" acp on ac.parentid=acp.id where ac.status=1 and a.id=? ",id);
	}
	/**
	 * 根据分类码查询有限条数
	 * @param cateCode
	 * @param limit
     * @return
     */
	public List<Article> qryListByCateCode(String cateCode,int limit){
		String dataType= PropKit.use(Constant.SYSTEM).get("db_type");
		String sql="select a.*,ac.name cate_name,acp.name pcate_name from "+tableName+" a left join "+ArticleCate.tableName+" ac on ac.id=a.cate_id left join "+ArticleCate.tableName+" acp on ac.parentid=acp.id where ac.status=1 and ac.code=? order by a.create_datetime desc";
		if("mysql".equals(dataType)) {
			return this.find(sql+" limit ? ",cateCode, limit);
		}else if("postgresql".equals(dataType)) {
			return this.find(sql +" limit ? offset 0",cateCode, limit);
		}
		return new ArrayList<Article>();
	}

	/**
	 * 查询固定数文章
	 * @param limit
	 * @return
     */
	public List<Article> qryList4Limit(int limit){
		String dataType= PropKit.use(Constant.SYSTEM).get("db_type");
		String sql="select a.*,ac.name cate_name,acp.name pcate_name from "+tableName+" a left join "+ArticleCate.tableName+" ac on ac.id=a.cate_id left join "+ArticleCate.tableName+" acp on ac.parentid=acp.id where ac.status=1 order by a.create_datetime desc";
		if("mysql".equals(dataType)) {
			return this.find(sql+" limit ? ", limit);
		}else if("postgresql".equals(dataType)) {
			return this.find(sql +" limit ? offset 0", limit);
		}
		return new ArrayList<Article>();
	}
}
